package kr.or.kosta.otr.controller.interestcontroller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import kr.or.kosta.otr.service.interestservice.InterestService;
import kr.or.kosta.otr.vo.CompanyReviewVO;
import kr.or.kosta.otr.vo.CompanyVO;
import kr.or.kosta.otr.vo.InterestCompanyVO;
import kr.or.kosta.otr.vo.InterestReviewVO;
import kr.or.kosta.otr.vo.TrueOrFalseVO;
import kr.or.kosta.otr.vo.UserVO;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class InterestController {
	@Resource(name = "InterestService")
	InterestService interestService;


	@RequestMapping(value = "/addInterestCompany.action")
	public ModelAndView addInterestCompany(@RequestParam(value="companyId") int companyId,
			HttpServletRequest request
			) throws SQLException {
		//userVo 받아오기
		HttpSession session = request.getSession();
		UserVO userVo = (UserVO) session.getAttribute("userVo");

		//해당 아이디에 해당 기업이 있는지 체크하기
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("companyId", companyId);
		map.put("userId", userVo.getUserId());
		boolean isExist = interestService.checkInterestCompany(map);
		String message = null;

		if(isExist){//존재하지 않는다.
			//companyVo 받아오기
			CompanyVO cvo = interestService.getOneCompany(companyId);
			
			//insert
			InterestCompanyVO interestCompanyVO = new InterestCompanyVO(0, cvo, userVo);
			interestService.addInterestCompany(interestCompanyVO);

			message = "관심 기업에 추가되셨습니다.";
		}else{
			message = "이미 관심기업에 존재합니다.";
		}
		return new ModelAndView("JsonView", "message",message);
	}

	@RequestMapping(value = "/deleteInterestCompany.action")
	public ModelAndView deleteInterestCompany(@RequestParam(value="interestCompanyId") int interestCompanyId) throws SQLException {

		interestService.deleteInterestCompany(interestCompanyId);
		String flag = "company";

		return new ModelAndView("forward:/getAllInterest.action?flag="+flag);
	}

	@RequestMapping(value = "/getAllInterest.action")
	public ModelAndView getAllInterest(
			HttpServletRequest request,
			HttpSession session) throws SQLException {

		String flag = request.getParameter("flag");	
		if(flag == "company")
			flag = "review";
		if(flag == "review")
			flag = "company";
		
		
		//interest Company 리스트 가져오기
		UserVO userVo = (UserVO) session.getAttribute("userVo");
		ArrayList<InterestCompanyVO> icList = interestService.getAllInterestCompany(userVo.getUserId());
	
		//Interest Review 리스트 가져오기
		//companyReviewVerify 가져오기
		
		ArrayList<InterestReviewVO> irList = interestService.getAllInterestReview(userVo.getUserId());
		
		ArrayList<TrueOrFalseVO> crvList  = new ArrayList<TrueOrFalseVO>();
		for(int i=0 ; i<irList.size() ; i++){
			int reviewId = irList.get(i).getCompanyReviewVO().getCompanyReviewId();
			
			ArrayList<TrueOrFalseVO> list = interestService.getCompanyReviewVerifyByInterestReview(reviewId);
			
			for(int j=0 ; j<list.size() ; j++){
					crvList.add(list.get(j));
			}
		}
		
		
		LinkedHashMap<String, ArrayList<TrueOrFalseVO>> linkmap = new LinkedHashMap<String, ArrayList<TrueOrFalseVO>>();
		int count=1;
		//진실 혹은 거짓 바인딩
		for (int i = 0; i < crvList.size();) {
			//각 리뷰에 대한 바인딩
			String userId = count
					+ " "
					+ crvList.get(i).getCompanyReviewVerifyVO()
					.getCompanyReviewVO().getCompanyReviewUserId();
			ArrayList<TrueOrFalseVO> tfList = new ArrayList<TrueOrFalseVO>();

			// 리뷰 진실 거짓 값 넣어주기

			//truth(진실)을 누른사람들을 넣은 것 -> 이거를 토크나이저로 잘라 숫자를 센다.
			String truth = crvList.get(i).getTruth();
			StringTokenizer tk1 = new StringTokenizer(truth, ",");

			int countT = 0;

			while (tk1.hasMoreTokens()) {
				countT++;
				tk1.nextToken();
			}
			crvList.get(i).setT(countT);

			//objection을 누른 사람들을 토크나이저로 잘라 수를 세서 o 에 바인딩
			String objection = crvList.get(i).getObjection();
			int countF = 0;
			StringTokenizer tk2 = new StringTokenizer(objection, ",");
			while (tk2.hasMoreTokens()) {
				countF++;
				tk2.nextToken();
			}
			crvList.get(i).setO(countF);

			tfList.add(crvList.get(i++));
		
			// 장점 진실 거짓 값 넣어주기
			String js = crvList.get(i).getTruth();
			int jconutT = 0;
			StringTokenizer jtk1 = new StringTokenizer(js, ",");
			while (jtk1.hasMoreTokens()) {
				jconutT++;
				jtk1.nextToken();
			}
			crvList.get(i).setT(jconutT);

			String job = crvList.get(i).getObjection();
			int jocountF = 0;
			StringTokenizer jtk2 = new StringTokenizer(job, ",");
			while (jtk2.hasMoreTokens()) {
				jocountF++;
				jtk2.nextToken();
			}
			crvList.get(i).setO(jocountF);

			tfList.add(crvList.get(i++));

			// 거짓 진실 거짓 값 넣어주기
			String ks = crvList.get(i).getTruth();
			int kcountT = 0;
			StringTokenizer ktk1 = new StringTokenizer(ks, ",");
			while (ktk1.hasMoreTokens()) {
				kcountT++;
				ktk1.nextToken();
			}
			crvList.get(i).setT(kcountT);

			String kob = crvList.get(i).getObjection();
			int kcountF = 0;
			StringTokenizer ktk2 = new StringTokenizer(kob, ",");
			while (ktk2.hasMoreTokens()) {
				kcountF++;
				ktk2.nextToken();
			}
			crvList.get(i).setO(kcountF);

			tfList.add(crvList.get(i++));


			linkmap.put(userId, tfList);
			count++;
		}
		
		//ModelAndView엔 바인딩
		ModelAndView mav = new ModelAndView();
		mav.addObject("icList", icList);
		mav.addObject("crv", linkmap);
		//mav.addObject("irList", irList);
		mav.addObject("flag", flag);
		mav.setViewName("/user/user_interest");

		return mav;
	}

	@RequestMapping(value = "/addInterestReview.action")
	public ModelAndView addInterestReview(
			@RequestParam(value="companyReviewId") int companyReviewId,
			HttpSession session) throws SQLException {
		
		//userVo 받아오기
		UserVO userVo = (UserVO) session.getAttribute("userVo");
		
		//interestReview 있는지 검색
		String message = "관심 리뷰에 추가되었습니다.";
		boolean isExist = false;
		
		ArrayList<InterestReviewVO> irList = interestService.getAllInterestReview(userVo.getUserId());
		for(InterestReviewVO irvo : irList){
			if(irvo.getCompanyReviewVO().getCompanyReviewId() == companyReviewId){
				message = "해당 리뷰는 이미 관심리뷰에 있습니다.";
				isExist = true;
			}
		}
		
		//companyReview 받아오기
		if(isExist == false){
			CompanyReviewVO crvo = interestService.getOneCompanyReviewById(companyReviewId);
			InterestReviewVO irvo = new InterestReviewVO(0, crvo, userVo);
			interestService.addInterestReview(irvo);
		}
		
		return new ModelAndView("JsonView","message",message);
	}

	@RequestMapping(value = "/deleteInterestReview.action")
	public ModelAndView deleteInterestReview(
			@RequestParam(value="companyReviewId") int companyReviewId,
			HttpSession session
			) throws SQLException {
		
		UserVO userVo = (UserVO) session.getAttribute("userVo");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userVo.getUserId());
		map.put("companyReviewId", companyReviewId);
		
		interestService.deleteInterestReview(map);
		String flag = "review";

		return new ModelAndView("forward:/getAllInterest.action?flag="+flag);
	}
	
	@RequestMapping(value="/exceldownload.action")
	public ModelAndView exceldownload(HttpSession session)throws SQLException{
		String error = null;
		UserVO userVo = (UserVO) session.getAttribute("userVo");
		
		if(userVo.getUserPoint() >= 20){
			ArrayList<InterestCompanyVO> icList = interestService.getAllInterestCompany(userVo.getUserId());
			if(icList.size() != 0){
				ArrayList<CompanyVO> cList = new ArrayList<CompanyVO>();
				for(InterestCompanyVO ic: icList)
					cList.add(ic.getCompanyVo());

				Map<String,Object> ModelMap = new HashMap<String, Object>();
				ModelMap.put("cList", cList);
				
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("point", 20);
				map.put("userId", userVo.getUserId());
				interestService.updatePointMinus(map);
				
				int point = userVo.getUserPoint();
				userVo.setUserPoint(point-20);
				return new ModelAndView("excelView",ModelMap);
			}
		}
		else {
			error = "point";
		}
		
		return new ModelAndView("error","error",error);
	}
}
